package cn.com.fssg.platform.base.handler.impl.gsl.lz;

import cn.com.fssg.platform.base.handler.InterfaceHandler;
import cn.com.fssg.platform.biz.BizUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Description: 工商联履职审核接口
 */
@Component
public class GslLzAssCtl implements InterfaceHandler {

    private NamedParameterJdbcTemplate jdbcTemplate = BizUtil.cur().tenantMainJdbcTemplate();

//    @Autowired
//    private NamedParameterJdbcTemplate jdbcTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object run(HttpServletRequest request, JSONObject jsonObject) throws Exception {
        // 获取所有履职填报信息
        JSONArray dataList = jsonObject.getJSONArray("dataList");
        if (dataList == null || dataList.isEmpty()) {
            throw new Exception("没有需要处理的数据");
        }

        // 构建ID列表并创建SQL查询
        List<String> ids = new ArrayList<>();
        for (Object item : dataList) {
            JSONObject jsonItem = (JSONObject) item;
            String id = jsonItem.getString("id");
            if (id != null && !id.isEmpty()) {
                ids.add(id);
            }
        }

        if (ids.isEmpty()) {
            throw new Exception("没有有效的ID数据");
        }

        String queryAccSql = "SELECT * FROM gsl_assessment_content WHERE id IN (" +
                StringUtils.join(ids.stream().map(id -> "'" + id + "'").collect(Collectors.toList()), ",") + ")";

        List<Map<String, Object>> accList = jdbcTemplate.queryForList(queryAccSql, new HashMap<>());
        if (accList == null || accList.isEmpty()) {
            throw new Exception("数据不存在");
        }

        List<Map<String, Object>> list = new ArrayList<>();
        Set<String> processedIds = new HashSet<>(); // 用于跟踪已处理的ID

        for (Object item : dataList) {
            JSONObject jsonItem = (JSONObject) item;
            String id = jsonItem.getString("id");

            // 查找匹配的评估内容
            Optional<Map<String, Object>> accOptional = accList.stream()
                    .filter(acc -> id.equals(String.valueOf(acc.get("id"))))
                    .findFirst();

            if (!accOptional.isPresent()) {
                continue; // 跳过未找到的记录
            }

            Map<String, Object> ac = new HashMap<>(accOptional.get());
            String auditState = String.valueOf(ac.getOrDefault("audit_state", ""));

            // 只处理未审核的记录
            if (!"1".equals(auditState)) {
                ac.put("audit_sc", jsonItem.getOrDefault("audit_sc", "1"));
                ac.put("audit_state", "1");
//                ac.put("subject_name", jsonItem.getOrDefault("subject_name", ""));
                ac.put("audit_info", jsonItem.getOrDefault("audit_info", "您已通过审核"));
                ac.put("audit_user_id", BizUtil.cur().curUserId());
                ac.put("audit_date", new Date());

                list.add(ac);
                processedIds.add(id); // 标记为已处理
            }
        }

        if (list.isEmpty()) {
            return null;
        }

        // 分组处理通过和不通过的记录
        List<Map<String, Object>> sc = list.stream()
                .filter(item -> "1".equals(String.valueOf(item.getOrDefault("audit_sc", ""))))
                .collect(Collectors.toList());

        List<Map<String, Object>> sb = list.stream()
                .filter(item -> "2".equals(String.valueOf(item.getOrDefault("audit_sc", ""))))
                .collect(Collectors.toList());

        // 构建消息内容
        StringBuilder infoBuilder = new StringBuilder("您好，您提交的本季度履职考核内容已审核通过的项目有:");
        String assId = "";
        String createBy = "";

        // 处理通过的项目
        if (!sc.isEmpty()) {
            Map<String, Map<String, Object>> contentMap = sc.stream()
                    .filter(item -> item.get("assessment_subject_id") != null)
                    .collect(Collectors.toMap(
                            item -> String.valueOf(item.get("assessment_subject_id")),
                            item -> item,
                            (existing, replacement) -> existing
                    ));

            for (Map.Entry<String, Map<String, Object>> entry : contentMap.entrySet()) {
                Map<String, Object> v = entry.getValue();

                if (assId.isEmpty()) {
                    assId = String.valueOf(v.getOrDefault("assessment_id", ""));
                    createBy = String.valueOf(v.getOrDefault("create_by", ""));
                }

                infoBuilder.append(v.getOrDefault("subject_name", "")).append(",");
            }
        } else {
            infoBuilder.append("暂无。");
        }

        // 处理不通过的项目
        infoBuilder.append("本季度履职考核内容不通过的项目有:");
        if (!sb.isEmpty()) {
            Map<String, Map<String, Object>> contenSbtMap = sb.stream()
                    .filter(item -> item.get("assessment_subject_id") != null)
                    .collect(Collectors.toMap(
                            item -> String.valueOf(item.get("assessment_subject_id")),
                            item -> item,
                            (existing, replacement) -> existing
                    ));

            for (Map.Entry<String, Map<String, Object>> entry : contenSbtMap.entrySet()) {
                Map<String, Object> v = entry.getValue();

                if (assId.isEmpty()) {
                    assId = String.valueOf(v.getOrDefault("assessment_id", ""));
                    createBy = String.valueOf(v.getOrDefault("create_by", ""));
                }

                infoBuilder.append(v.getOrDefault("subject_name", "")).append(",");
            }
        } else {
            infoBuilder.append("暂无。");
        }
        if (StringUtils.equals(jsonObject.get("is_sms").toString(), "is")) {
            sendMsg(infoBuilder, sc, assId, createBy, list);
        }

        // 保存审核日志
        Map<String, Object> auditLog = new HashMap<>();
        auditLog.put("id", BizUtil.cur().getSnowflakeIdStr());
        auditLog.put("create_by", BizUtil.cur().curUserId());
        auditLog.put("update_by", BizUtil.cur().curUserId());
        auditLog.put("create_date", new Date());
        auditLog.put("update_date", new Date());
        auditLog.put("del_flag", "0");
        auditLog.put("user_id", BizUtil.cur().curUserId());

        //获取人员信息    wx_user
        String queryUserSql = "select * from wx_user where id = :id";
        Map<String, Object> wxUserParam = new HashMap<>();
        wxUserParam.put("id", createBy);
        List<Map<String, Object>> users = jdbcTemplate.queryForList(queryUserSql, wxUserParam);
        Map<String, Object> user = users.isEmpty() ? null : users.get(0);
        if (user != null) {
            auditLog.put("user_name", user.get("username"));
        }

        auditLog.put("ass_id", assId);
        auditLog.put("type", "1");

        // 保存审核结果和日志
        return saveAssessmentContent(createBy, list, auditLog);
    }

    public int sendMsg(StringBuilder infoBuilder, List<Map<String, Object>> sc, String assId, String createBy, List<Map<String, Object>> list) {
        // 添加总分信息
        infoBuilder.append("请您重新登录系统，按照审核意见进行修改后重新提交。目前您的履职考核总得分为");

        Map<String, Object> param = new HashMap<>();
        param.put("assessment_id", assId);
        param.put("audit_sc", "1");
        param.put("create_by", createBy);
        String querySql1 = "select * from gsl_assessment_content where assessment_id=:assessment_id and audit_sc=:audit_sc and create_by=:create_by";
        List<Map<String, Object>> assessmentContents = jdbcTemplate.queryForList(querySql1, param);
        if (assessmentContents.isEmpty()) {
            assessmentContents = new ArrayList<>();
        }
        assessmentContents.addAll(sc);
        Map<String, Map<String, Object>> map = assessmentContents.stream()
                .filter(item -> item.get("assessment_subject_id") != null) // 确保键不为空
                .collect(Collectors.toMap(
                        item -> String.valueOf(item.get("assessment_subject_id")), // 键：assessment_subject_id
                        item -> item, // 值：整个Map对象
                        (val1, val2) -> val1 // 合并函数：保留第一个值
                ));


        final Integer[] all = {0};
        map.forEach((k, v) -> {
            String querySql2 = "select * from gsl_assessment_subject where id=:id";
            Map<String, Object> param2 = new HashMap<>();
            param2.put("id", v.get("assessment_subject_id"));
            List<Map<String, Object>> rtList = jdbcTemplate.queryForList(querySql2, param2);
            if(!rtList.isEmpty()) {
                Map<String, Object> rt = rtList.get(0);
                all[0] = (all[0] + Integer.parseInt(rt.get("subject_fraction").toString()));
            }
        });
        String querySql3 = "select * from wx_user where id=:id";
        Map<String, Object> param3 = new HashMap<>();
        param3.put("id", createBy);
        List<Map<String, Object>> userList = jdbcTemplate.queryForList(querySql3, param3);
        if(!userList.isEmpty()) {
            Map<String, Object> zw = userList.get(0);
            String querySql4 = "select * from gsl_zw_info where zw_id=:zw_id";
            Map<String, Object> param4 = new HashMap<>();
            param4.put("zw_id", zw.get("id"));
            List<Map<String, Object>> zwInfoList = jdbcTemplate.queryForList(querySql4, param4);
            if(!zwInfoList.isEmpty()) {
                Map<String, Object> zi = zwInfoList.get(0);
                if (Objects.equals(zi.get("is_cadre"), "0")) {
                    all[0] = 0;
                }
            }
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        infoBuilder.append(all[0].toString()).append("分。");
        Map<String, Object> smsVo = new HashMap<>();
        smsVo.put("key", BizUtil.cur().getSnowflakeIdStr());
        smsVo.put("info", infoBuilder.toString());
        smsVo.put("create_date", sdf.format(new Date()));

        Map<String, Object> param5 = new HashMap<>();
        param5.put("id", list.get(0).get("create_by"));
        List<Map<String, Object>> userLists = jdbcTemplate.queryForList(querySql3, param5);
        if (!userLists.isEmpty()) {
            Map<String, Object> wxUser = userLists.get(0);
            smsVo.put("phone", wxUser.get("phone"));
            smsVo.put("state", "0");
            smsVo.put("type", "1");
            smsVo.put("create_by", wxUser.get("id"));
//            redisUtil.hset(Sender.SMS_INFO, smsVo.getKey(), smsVo);
//            redisUtil.sender(smsVo, "0", gslSmsService);
        }
        return 0;
    }

    public int saveAssessmentContent(String createBy, List<Map<String, Object>> list, Map<String, Object> auditLog) {
        Date start = getCurrYearFirst();
        Date end = getCurrYearLast();
        String querySql = "select * from gsl_assessment_content where create_by = :create_by and audit_sc = '1' and create_date between :start and :end";
        Map<String, Object> param = new HashMap<>();
        param.put("create_by", createBy);
        param.put("start", start);
        param.put("end", end);
        List<Map<String, Object>> fsList = jdbcTemplate.queryForList(querySql, param);
        String assId = list.get(0).get("assessment_id").toString();
        String querySql1 = "select * from gsl_assessment where id = :id";
        Map<String, Object> param1 = new HashMap<>();
        param1.put("id", assId);
        List<Map<String, Object>> assessmentList = jdbcTemplate.queryForList(querySql1, param1);
        if (!assessmentList.isEmpty()) {
            Map<String, Object> assessment = assessmentList.get(0);
            //year1如何等于year2就表示是今年的审核内容，那么就添加到fslist
            String date2 = assessment.get("create_date").toString();
            DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                    .appendPattern("yyyy-MM-dd HH:mm:ss")
                    .appendFraction(ChronoField.MILLI_OF_SECOND, 1, 3, true) // 处理毫秒部分
                    .toFormatter();

            // 解析为 LocalDateTime
            LocalDateTime localDateTime = LocalDateTime.parse(date2, formatter);

            // 转换为 Date 对象
            Date date = Date.from(localDateTime.atZone(java.time.ZoneId.systemDefault()).toInstant());
            String year1 = getDateString(date, "yyyy");
            String year2 = getDateString(new Date(), "yyyy");
            if (StringUtils.equals(year1, year2)) {
                List<Map<String, Object>> assessmentContents = list.stream().filter(assessmentContent -> Objects.equals(assessmentContent.get("audit_sc"), "1")).collect(Collectors.toList());
                if (assessmentContents != null && assessmentContents.size() > 0) {
                    fsList.addAll(assessmentContents);
                }
            }
            String querySql2 = "select * from gsl_zw_info where zw_id=:zw_id";
            Map<String, Object> param2 = new HashMap<>();
            param2.put("zw_id", createBy);
            List<Map<String, Object>> zwInfoList = jdbcTemplate.queryForList(querySql2, param2);
            if (!zwInfoList.isEmpty()) {
                Map<String, Object> zwInfo = zwInfoList.get(0);
                final Integer[] all = {0};
                if (Objects.equals(zwInfo.get("is_cadre"), "1")) {
                    if (!fsList.isEmpty()) {
                        Map<String, Map<String, Object>> map = fsList.stream()
                                .filter(item -> item.get("assessment_subject_id") != null)
                                .collect(Collectors.toMap(
                                        item -> String.valueOf(item.get("assessment_subject_id")),
                                        item -> item,
                                        (val1, val2) -> val1
                                ));
                        map.forEach((k, v) -> {
                            String querySql4 = "select * from gsl_assessment_subject where id=:id";
                            Map<String, Object> param4 = new HashMap<>();
                            param4.put("id", v.get("assessment_subject_id"));
                            List<Map<String, Object>> dataLists = jdbcTemplate.queryForList(querySql4, param4);
                            Map<String, Object> data = dataLists.get(0);
                            all[0] = (all[0] + Integer.parseInt(data.get("subject_fraction").toString()));
                        });
                    }
                    String querySql3 = "select * from wx_user where id=:id";
                    Map<String, Object> param3 = new HashMap<>();
                    param3.put("id", createBy);
                    List<Map<String, Object>> userList = jdbcTemplate.queryForList(querySql3, param3);
                    if (!userList.isEmpty()) {
                        Map<String, Object> wxUser = userList.get(0);
                        Map<String, Object> data = new HashMap<>();
                        data.put("zw_id", wxUser.get("id"));
                        data.put("phone", wxUser.get("phone"));
                        data.put("zw_name", wxUser.get("username"));
                        data.put("fraction", all[0]);

                        data.put("update_by", BizUtil.cur().curUserId());
                        data.put("create_by", BizUtil.cur().curUserId());
                        data.put("update_date", new Date());
                        data.put("create_date", new Date());
                        data.put("del_flag", "0");
                        data.put("id", BizUtil.cur().getSnowflakeIdStr());
                        insertDatabase(data, "gsl_topten");
                    }
                }
            }
            list.forEach(item -> {
                //验证是否存在
                String querySql3 = "select * from gsl_assessment_content where id=:id";
                Map<String, Object> param3 = new HashMap<>();
                param3.put("id", item.get("id"));
                List<Map<String, Object>> dataLists = jdbcTemplate.queryForList(querySql3, param3);
                if (!dataLists.isEmpty()) {
                    updateDatabase(item, "gsl_assessment_content");
                } else {
                    insertDatabase(item, "gsl_assessment_content");
                }

            });
            insertDatabase(auditLog, "gsl_audit_log");
        }


        return 0;
    }

    /** 新增数据库数据 */
    public int insertDatabase(Map<String, Object> param, String tableName) {
        List<String> fields = new ArrayList<>();
        List<String> placeholders = new ArrayList<>();
        param.forEach((k, v) -> {
            if (v != null) {
                fields.add(k);
                placeholders.add(":" + k);
            }
        });

        String sql = String.format("INSERT INTO %s (%s) VALUES (%s)",
                tableName,
                String.join(", ", fields),
                String.join(", ", placeholders)
        );
        return jdbcTemplate.update(sql, param);
    }

    public int updateDatabase(Map<String, Object> param, String tableName) {
        List<String> fields = new ArrayList<>();
        param.forEach((k, v) -> {
            if (v != null && !"id".equals(k)) {
                fields.add(k + " = :" + k);
            }
        });

        String sql = String.format("UPDATE %s SET %s WHERE id = '%s'",
                tableName,
                String.join(", ", fields),
                param.get("id")
        );
        return jdbcTemplate.update(sql, param);
    }

    public static Date getCurrYearFirst() {
        Calendar currCal = Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearFirst(currentYear);
    }

    public static Date getYearFirst(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;
    }

    public static Date getCurrYearLast() {
        Calendar currCal = Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearLast(currentYear);
    }

    public static Date getYearLast(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        Date currYearLast = calendar.getTime();
        return currYearLast;
    }

    public static String getDateString(Date date, String formt) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formt);

        return simpleDateFormat.format(date);
    }
}